package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Members;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.MembersMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.IMembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 成员管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-25
 */
@Service
public class MembersServiceImpl implements IMembersService {
    @Autowired
    private MembersMapper membersMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 查询成员
     *
     * @param id 成员主键
     * @return 成员
     */
    @Override
    public Members selectMembersByMemberId(Long id) {
        return membersMapper.selectMembersByMemberId(id);
    }

    /**
     * 查询成员列表
     *
     * @param members 成员
     * @return 成员
     */
    @Override
    public List<Members> selectMembersList(Members members) {
        Long userId = SecurityUtils.getUserId();
        List<SysRole> sysRoles = sysRoleMapper.selectRolesByUserId(userId);
        List<String> roleName = sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
        PageUtils.startPage();
        if (roleName.contains("超级管理员")) {
            return membersMapper.selectMembersList(members);
        }

        return membersMapper.selectMembersListByUserId(members, userId);
    }

    /**
     * 新增成员
     *
     * @param members 成员
     * @return 结果
     */
    @Override
    public int insertMembers(Members members) {
        Long userId = SecurityUtils.getUserId();
        members.setUserId(userId);
        return membersMapper.insertMembers(members);
    }

    /**
     * 修改成员
     *
     * @param members 成员
     * @return 结果
     */
    @Override
    public int updateMembers(Members members) {

        Members old = membersMapper.selectMembersByMemberId(members.getId());
        if (!old.getRole().equals(members.getRole())) {

            SysUserRole role = new SysUserRole();
            role.setRoleId(100L);
            role.setUserId(members.getUserId());
            if (members.getRole() > 0 && old.getRole() == 0) {
                List<SysUserRole> list = new ArrayList<>();
                list.add(role);
                try {
                    userRoleMapper.batchUserRole(list);
                } catch (Exception e) {
                    System.out.println("授权失败!");
                }
            } else if (old.getRole() > 0 && members.getRole() == 0) {
                userRoleMapper.deleteUserRoleInfo(role);
            }

        }

        return membersMapper.updateMembers(members);
    }

    /**
     * 批量删除成员
     *
     * @param ids 需要删除的成员主键
     * @return 结果
     */
    @Override
    public int deleteMembersByMemberIds(Long[] ids) {
        return membersMapper.deleteMembersByMemberIds(ids);
    }

    /**
     * 删除成员信息
     *
     * @param id 成员主键
     * @return 结果
     */
    @Override
    public int deleteMembersByMemberId(Long id) {
        return membersMapper.deleteMembersByMemberId(id);
    }

    /**
     * 审核通过成员申请
     *
     * @param members 成员信息
     * @return 结果
     */
    @Override
    public int approveMembers(Members members) {

        //添加权限

        Long userId = SecurityUtils.getUserId();


        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(userId);
        userRole.setRoleId(2L);
        // 批量更新成员状态为已通过(1)，并设置审核时间
        if (members.getMemberIds() != null && members.getMemberIds().length > 0) {
            // 过滤掉null值
            Long[] validIds = java.util.Arrays.stream(members.getMemberIds())
                    .filter(id -> id != null)
                    .toArray(Long[]::new);

            if (validIds.length > 0) {
                members.setReviewedAt(new Date());
                return membersMapper.updateMembersStatus(validIds, 2, members.getReviewedAt());
            }
        }
        return 0;
    }

    /**
     * 拒绝成员申请
     *
     * @param members 成员信息
     * @return 结果
     */
    @Override
    public int rejectMembers(Members members) {
        // 批量更新成员状态为已拒绝(2)，并设置审核时间和拒绝原因
        if (members.getMemberIds() != null && members.getMemberIds().length > 0) {
            // 过滤掉null值
            Long[] validIds = java.util.Arrays.stream(members.getMemberIds())
                    .filter(id -> id != null)
                    .toArray(Long[]::new);

            if (validIds.length > 0) {
                members.setReviewedAt(new Date());
                return membersMapper.updateMembersStatusWithComment(validIds, 3, members.getReviewedAt(), members.getRejectReason());
            }
        }
        return 0;
    }

    @Override
    public int unapply(Long clubId, Long userId) {
        return membersMapper.unapply(clubId, userId);
    }

    @Override
    public List<Members> getInfoByClubId(Long id) {
        return membersMapper.getInfoByClubId(id);
    }
} 